import { ColorSchema } from '@amcax/base';
import { i18n } from '@app-nextmesh/common/utils';
import { CommandDialog2 } from '@app-nextmesh/components/Dialogs';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import {
  IComponent,
  NMMeshBaseCommand,
  NMToolCmdDialogParams,
} from '@app-nextmesh/types';
import { updateModelsColor } from '@app-nextmesh/utils';
import { IChangeEvent } from '@rjsf/core';
import { RJSFSchema } from '@rjsf/utils';
import { useState } from 'react';

function CmdComponentAddDialog({
  title,
  onClose: handleOnClose,
  params,
}: NMToolCmdDialogParams<{ id: string; formData: IComponent }>) {
  const [formData, setFormData] = useState<IComponent>(params?.formData);
  const [loading, setLoading] = useState<boolean>(false);
  const { projectInfo, setProjectInfo } = useProjectStore();

  const schema: RJSFSchema = {
    type: 'object',
    required: ['name', 'color'],
    properties: {
      name: {
        type: 'string',
      },
      color: {
        type: 'string',
        default: ColorSchema.view.shellString,
      },
    },
  };
  const uiSchema = {
    color: {
      'ui:widget': 'colorPicker',
    },
  };

  const onClose = () => {
    if (formData?.color && formData?.objects) {
      // 当objects不为空时，同步更新渲染场景的几何/网格颜色
      updateModelsColor(formData.color, formData.objects);
    }
    handleOnClose();
  };

  const onChange = (data: IChangeEvent) => {
    const newFormData = data.formData;
    if (newFormData?.color && formData?.objects) {
      // 当objects不为空时，同步更新渲染场景的几何/网格颜色
      updateModelsColor(newFormData.color, formData.objects);
    }
  };

  const onSubmit = async (data) => {
    setFormData({ ...formData, ...data });
    try {
      setLoading(true);
      let newCom: IComponent = null;
      if (data.uuid) {
        newCom = await documentV2.updateComponent(data);
        // update component
        const index = projectInfo.geometries?.findIndex(
          (item) => item.uuid === data.uuid,
        );
        if (index !== -1) {
          projectInfo.geometries[index] = newCom;
          setProjectInfo({ ...projectInfo });
        }
      } else {
        newCom = await documentV2.addComponent(data);
        // add component
        if (!projectInfo.geometries) {
          projectInfo.geometries = [];
        }
        projectInfo.geometries?.push(newCom);
        setProjectInfo({ ...projectInfo });
      }
      onClose();
    } finally {
      setLoading(false);
    }
  };

  return (
    <CommandDialog2
      title={title}
      formData={formData}
      schema={schema}
      extraUiSchema={uiSchema}
      onClose={onClose}
      onChange={onChange}
      onSubmit={onSubmit}
      submitLoading={loading}
    />
  );
}

export const cmdComponent: NMMeshBaseCommand = {
  id: 'cmdComponent',
  label: 'command.component.component',
  icon: 'commands/component/component',
  create: (label, onClose, _, params) => (
    <CmdComponentAddDialog
      title={i18n.t(label)}
      onClose={onClose}
      params={params}
    />
  ),
};
